package com.jz.netthings.utils;

import com.jz.netthings.exception.AdscmSystemException;
import org.apache.commons.lang.time.DateUtils;

import java.sql.SQLOutput;
import java.sql.Time;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author yyy
 * @ClassName AdscmDateUtils
 * @Description 时间工具类
 * @date 2018/8/13 17:24
 */
public class AdscmDateUtils {


    /**
     * 格式化时间为秒
     * @param min 格式：mm:ss  分:秒
     * @return
     */
    public static String minToSeconds(String min) {
        String seconds = null;
        if (AdscmBaseUtils.getInstance().isNotEmpty(min,null)){
            String[] arraymin = min.split(":");
            String minStr = arraymin[0];
            String sStr = arraymin[1];
            Integer minInt = Integer.valueOf(minStr) * 60;
            Integer sInt = Integer.valueOf(sStr);
            sInt = minInt + sInt;
            seconds = String.valueOf(sInt);
        }
        return seconds;
    }

    /**
     * 格式化秒为： xx分xx秒
     * @param seconds
     * @return
     */
    public static String getInputSecondsOuptMin(Integer seconds) {
        if (seconds < 60) {
            return String.valueOf(seconds) + "秒";
        } else {
            Integer min = seconds / 60;
            Integer s = seconds % 60;
            if (s == 0) {
                return String.valueOf(min) + "分";
            }
            return String.valueOf(min) + "分" + String.valueOf(s) + "秒";
        }
    }

    /**
     * 得到指定日期所在的周是从那天开始 到哪天结束的，是多少周
     * @param time
     * @return
     * @throws ParseException
     */
    public static Map<String, Object> getWeekByDate(Date time) throws ParseException {
        Map<String, Object> map=new HashMap<String, Object>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 设置时间格式
        Calendar cal = Calendar.getInstance();
        cal.setTime(time);
        // 判断要计算的日期是否是周日，如果是则减一天计算周六的，否则会出问题，计算到下一周去了
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
        if (1 == dayWeek) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
        System.out.println("要计算日期为:" + sdf.format(cal.getTime())); // 输出要计算日期
        cal.setFirstDayOfWeek(Calendar.MONDAY);// 设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        int day = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);// 根据日历的规则，给当前日期减去星期几与一个星期第一天的差值
        String imptimeBegin = sdf.format(cal.getTime());
        System.out.println("所在周星期一的日期：" + imptimeBegin);
        cal.add(Calendar.DATE, 6);
        String imptimeEnd = sdf.format(cal.getTime());
        System.out.println("所在周星期日的日期：" + imptimeEnd);
//        if (time.getTime()>=sdf.parse(imptimeBegin).getTime()&&cal.getTime().getTime()<=sdf.parse(imptimeEnd).getTime()) {
            map.put("benginDate", imptimeBegin);
            map.put("endDate", imptimeEnd);
            map.put("whereWeek", cal.get(Calendar.WEEK_OF_YEAR));
//        }
        return map;
    }
    public static int getWeek(Date time,Date time1) throws ParseException {
        Calendar cal = Calendar.getInstance();
        cal.setTime(time);
        // 判断要计算的日期是否是周日，如果是则减一天计算周六的，否则会出问题，计算到下一周去了
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
        if (1 == dayWeek) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }

        int a=cal.get(Calendar.WEEK_OF_YEAR);
        cal.setTime(time1);
        int b=cal.get(Calendar.WEEK_OF_YEAR);


        return a-b;
    }

    /**
     * 判断指定日期是哪一周
     * @param time
     * @return
     * @throws ParseException
     */
    public static int getWeek(Date time) throws ParseException {
        Calendar cal = Calendar.getInstance();
        cal.setTime(time);
        // 判断要计算的日期是否是周日，如果是则减一天计算周六的，否则会出问题，计算到下一周去了
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
        if (1 == dayWeek) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }

        int a=cal.get(Calendar.WEEK_OF_YEAR);

        return a;
    }

    /**
     * 获取指定日期的前或者后num年/月/天，根据类型
     * @param type : 类型：type = Calendar.YEAR、Calendar.MONTH、Calendar.DATE
     * @return : yyyy-MM-dd
     */
    public static String getThatDateStr(Date date, int num, int type){
        return AdscmDateUtils.getNowOnlyDateFomat1(getThatDate(date,num,type));
    }
    /**
     * 获取指定日期的前或者后num年/月/天，根据类型
     * @param type : 类型：type = Calendar.YEAR、Calendar.MONTH、Calendar.DATE
     * @return : Date
     */
    public static Date getThatDate(Date date, int num, int type){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(type, num);
        date = calendar.getTime();
        return date;
    }
    /**
     * 获取指定日期当天的最后一秒钟
     * @return : Date
     */
    public static Date getThatDateTime(Date date){
        Date newDate = null;
        try{
            String d = new SimpleDateFormat("yyyyMMdd").format(date) + " 23:59:59";
            newDate = new SimpleDateFormat("yyyyMMdd HH:mm:ss").parse(d);
        }catch (Exception e){}
        return newDate;
    }
    /**
     * 获取指定日期的年、月、日
     * @return : Date
     */
    public static String[] getYearMonthDay(Date date){
        String[] result = new String[3];
        try{
            String d = new SimpleDateFormat("yyyyMMdd").format(date);
            result[0] = d.substring(0,4);
            result[1] = d.substring(4,6);
            result[2] = d.substring(6,8);
        }catch (Exception e){}
        return result;
    }

    /**
     * 将制定格式的字符串转换成日期，字符串格式：yyyy-MM-dd
     * @return
     */
    public static Date parseDate(String dateStr) throws AdscmSystemException{

        Date date = null;
        try {
            if(!AdscmBaseUtils.getInstance().isNotEmpty(dateStr,null)){
                dateStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            }
            date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
        } catch (ParseException e) {
            try{
                long dateLong = Long.parseLong(dateStr);
                date = new Date(dateLong);
            }catch (Exception e1){
                throw new AdscmSystemException(e.getMessage());
            }
        }
        return date;
    }
    /**
     * 将制定格式的字符串转换成日期，字符串格式：yyyyMMdd
     * @return
     */
    public static Date parseDate2(String dateStr) throws AdscmSystemException{

        Date date = null;
        try {
            date = new SimpleDateFormat("yyyyMMdd").parse(dateStr);
        } catch (ParseException e) {
            throw new AdscmSystemException(e.getMessage());
        }
        return date;
    }
    /**
     * 格式化指定日期，格式：yyyy-MM-dd
     * @return
     */
    public static String getNowOnlyDateFomat1(Date date){
        String dfs = new SimpleDateFormat("yyyy-MM-dd").format(date);
        return dfs;
    }

    /**
     * 格式化指定日期的前/后 N 年，格式：yyyy-MM-dd
     * @param date
     * @param num 可以为 正/负，对应指定日期的前/后 年
     * @return
     */
    public static String getNowOnlyDateFomat1(Date date,int num){

        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR,num);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dfs = formatter.format(calendar.getTime());
        return dfs;
    }
    /**
     * 格式化指定日期的前/后 N 年/月/日/时分秒，格式：yyyy-MM-dd HH:mm:ss
     * @param date
     * @param num 可以为 正/负，对应指定日期的前/后 年
     * @param type 类型
     * @return
     */
    public static String getNowOnlyDateFomat2(Date date,int num,int type){

        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(type,num);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dfs = formatter.format(calendar.getTime());
        return dfs;
    }

    public static void main(String[] args) {
        System.out.println(1000d/365d);
    }

    /**
     * 格式化指定日期，格式：yyyyMMdd
     * @return
     */
    public static String getNowOnlyDateFomat2(Date date){
        String dfs = new SimpleDateFormat("yyyyMMdd").format(date);
        return dfs;
    }

    /**
     * 格式化指定日期，格式：yyMMdd
     * @return
     */
    public static String getNowOnlyDateFomat3(Date date){
        String dfs = new SimpleDateFormat("yyMMdd").format(date);
        return dfs;
    }
    /**
     * 格式化指定日期，格式：yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String getDateFomat(Date date){
        String dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
        return dfs;
    }
    public static Date parseDateL(String date){
        Date s = null;
        try {
            s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);
        } catch (ParseException e) {
            try{
                long dateLong = Long.parseLong(date);
                s = new Date(dateLong);
            }catch (Exception e1){
                e1.printStackTrace();
            }
        }
        return s;
    }

    /**
     * 得到一个24小时制时间对应的12小时制时间
     * @param time
     * @return
     */
    public  static String getIntegerTime(String time){
        Date nowtime=null;
        try {
            nowtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar now=Calendar.getInstance();
        now.setTime(nowtime);
        int hour = now.get(Calendar.HOUR_OF_DAY);
        int min = now.get(Calendar.MINUTE);
        if (hour>12) {
            hour=hour-12;
        }
        String strHour = new DecimalFormat("00").format(hour);
        String strMin = new DecimalFormat("00").format(min);
        String intergerTime=strHour+":"+strMin;
        return intergerTime;
    }

    /**
     * 相差分钟数
     * @param beginDate
     * @param endDate
     * @return
     * @throws Exception
     */
    public static long betweenMinutes(String beginDate, String endDate) throws Exception {
        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date begin = dfs.parse(beginDate);
        Date end = dfs.parse(endDate);
        long between = (end.getTime() - begin.getTime()) / 1000;
        long min = between / 60;
        return min;
    }

    /**
     * 获取两个日期之间的间隔的每一天
     * @param startDate
     * @param endDate
     * @return
     */
    public static List<String> getBetweenDate(Date startDate,Date endDate){

        List<String> list = new ArrayList<>();
        try{
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String sdStr = format.format(startDate);
            String edStr = format.format(endDate);

            Date sdDate = format.parse(sdStr);
            Date edDate = format.parse(edStr);

            while (edDate.getTime() > sdDate.getTime()){
                list.add(AdscmDateUtils.getNowOnlyDateFomat2(sdDate));
                sdDate = AdscmDateUtils.getThatDate(sdDate,1,Calendar.DATE);
            }
            list.add(AdscmDateUtils.getNowOnlyDateFomat2(edDate));
        }catch (Exception e){
            e.printStackTrace();
        }

        return list;
    }
    /**
     * 传入一个时间，得到当前月的第一天 比如2018-06-01
     *
     * @param date
     * @return
     */
    public static Date getFirstDayOfTheMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        return calendar.getTime();
    }

    /**
     * 传入一个时间，得到当前月的最后一天 比如2018-06-30
     *
     * @param date
     * @return
     */
    public static Date getLastDayOfTheMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        // calendar.add(Calendar.MONTH, -1);
        calendar.set(Calendar.DAY_OF_MONTH,
                calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        return calendar.getTime();
    }
    /**
     * 传入一个时间，得到年
     *
     * @param date
     * @return
     */
    public static int getTheYear(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.YEAR);
    }
    /**
     * 传入一个时间，得到月
     *
     * @param date
     * @return
     */
    public static int getTheMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(Calendar.MONTH) + 1;
    }

    /**
     *根据一段日期算出中间是否有多少个周末
     * @param startDate
     * @param endDate
     * @return
     * @throws Exception
     */
    public  static  int getSunday(Date startDate,Date endDate) {
        int temp= 0;
        try {
            temp = 0;
            List<String> betweenDate = getBetweenDate(startDate, endDate);
            for (String date : betweenDate) {
                Date tempdate = parseDate2(date);
                boolean isSunDay = getIsSunDay(tempdate);
                if (isSunDay){
                    temp++;
                }
            }
        } catch (AdscmSystemException e) {
            e.printStackTrace();
        }

        return temp;
    }

    /**
     * 判断是否是周末
     * @param date
     * @return
     */
 public static boolean getIsSunDay( Date date){
        boolean result=false;
      Calendar cal = Calendar.getInstance();
      cal.setTime(date);
     int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
     if (w < 0)
         w = 0;
     if (w==0){
       return  true;
     }
        return result;
 }    
 public static Date getFormateDate( Date date){
     Date parse = null;
     try {
         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
         String format = dateFormat.format(date);
         parse = dateFormat.parse(format);
     } catch (ParseException e) {
         e.printStackTrace();
     }

     return parse;
 }
    /**
     * 由出生日期计算年龄
     * @param birthDay
     * @return
     * @throws Exception
     */
    public static int getAge(Date birthDay) {
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthDay)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;
            }else{
                age--;
            }
        }
        return age;
    }
    /**
     * 判断两个日期是否是同一天
     * @param day1
     * @param day2
     * @return
     * @throws Exception
     */
    public static boolean isSameDay(Date day1,Date day2) {
        return DateUtils.isSameDay(day1, day2);
    }
    /**
     * 根据ms格式化时间成00:00:00
     * @return
     * @throws Exception
     */
    public static String getFormatMs(Long ms) {
        long day=ms/(24*60*60*1000);
        long hour=(ms/(60*60*1000)-day*24);
        long min=((ms/(60*1000))-day*24*60-hour*60);
        long s=(ms/1000-day*24*60*60-hour*60*60-min*60);
        DecimalFormat decimalFormat =new DecimalFormat();
        decimalFormat.applyPattern("00");
        String fs = decimalFormat.format(s);
        String fmin = decimalFormat.format(min);
        String fhour = decimalFormat.format(hour);
        String time="";
         if (day>0){
             time = day+"天"+fhour+":"+fmin+":"+fs;
         }else {
             time = fhour+":"+fmin+":"+fs;
         }
        return  time;
    }


//判断两个日期之间相差天数
    public static final int daysBetween(Date early, Date late) {

        java.util.Calendar calst = java.util.Calendar.getInstance();
        java.util.Calendar caled = java.util.Calendar.getInstance();
        calst.setTime(early);
        caled.setTime(late);
        //设置时间为0时
        calst.set(java.util.Calendar.HOUR_OF_DAY, 0);
        calst.set(java.util.Calendar.MINUTE, 0);
        calst.set(java.util.Calendar.SECOND, 0);
        caled.set(java.util.Calendar.HOUR_OF_DAY, 0);
        caled.set(java.util.Calendar.MINUTE, 0);
        caled.set(java.util.Calendar.SECOND, 0);
        //得到两个日期相差的天数
        int days = ((int) (caled.getTime().getTime() / 1000) - (int) (calst
                .getTime().getTime() / 1000)) / 3600 / 24;

        return days;
    }

//    传入一个年月日时分秒，只返回日期
    public static String getDateFormat(Date dateTime){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date=  sdf.format(dateTime);
        return date;
    }


    //传入一个日期获取今天和明天
    public static String[] getTodayAndTomorrow(Date date){
        String[] dateArray = new String[2];
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        Date today=calendar.getTime();
        calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
        Date  tomorrow=calendar.getTime(); //这个时间就是日期往后推一天的结果
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(today);
        String dateString2 = formatter.format(tomorrow);
        dateArray[0]=dateString;
        dateArray[1]=dateString2;
        return dateArray;
    }

    /**
     * 得到轮次的时间,14天为一个轮次那么加14天
     *
     * @param date
     * @param day
     * @return
     */
    public static Date getRoundTime(Date date, Integer day) {
        long time = date.getTime();
        day = day * 24 * 60 * 60 * 1000; // 要加上的天数转换成毫秒数
        time += day; // 相加得到新的毫秒数
        return new Date(time); // 将毫秒数转换成日期

    }
    /**
     * 获取某个日期的最后一秒钟的时间字符串
     *
     * @param date
     * @return
     */
    public static String getDateLastSeconds(Date date) {
        return getNowOnlyDateFomat1(date) + " 23:59:59";
    }
    /**
     * 获取某个日期的第一秒钟的时间字符串
     *
     * @param date
     * @return
     */
    public static String getDateFirstSeconds(Date date) {
        return getNowOnlyDateFomat1(date) + " 00:00:00";
    }


    /**
     * 得到指定日期那一年的第一轮次的结束时间
     *
     * @param date
     * @return
     */
    public static Date getfirstRoundTime(Date date) {
        Date newDate = getYearFirstDayOfTheFrstMonth(date);
        Date oldDate = getLastYearLastDayOfTheLastMonth(newDate);
        Date firstRoundTime = getRoundTime(oldDate, 14);
        return firstRoundTime;

    }

    /**
     * 传入一个时间,得到当年的第一个月的第一天 如2018-06-15==>> 2018-01-01
     *
     * @param date
     * @return
     */
    public static Date getYearFirstDayOfTheFrstMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }
    /**
     * 获取上一年的最后一个月的最后一天
     *
     * @param date
     * @return
     */
    public static Date getLastYearLastDayOfTheLastMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, -1);
        calendar.set(Calendar.MONTH, 11);
        calendar.set(Calendar.DAY_OF_MONTH, 31);
        return calendar.getTime();

    }




}
